package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.api.VoiceApi;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }

    @Override
    public Voice getVoice() {

        Criteria criteria = Criteria.where("state").is(0);
        TypedAggregation typedAggregation=TypedAggregation.newAggregation(Voice.class,  Aggregation.match(criteria),//查询条件
                Aggregation.sample(1) );
        AggregationResults<Voice> aggregate = mongoTemplate.aggregate(typedAggregation, Voice.class);
        if (CollUtil.isNotEmpty(aggregate.getMappedResults())){
            return aggregate.getMappedResults().get(0);
        }
        return null;

    }

    @Override
    public void updatestate(ObjectId id) {
        Query query = new Query(Criteria.where("id").is(id));
        Update update = new Update();
      update.set("state", 1);
      mongoTemplate.updateFirst(query,update,Voice.class);
    }
}
